﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using WOIM_NET.Annotations;
using System.Net;

namespace WOIM_NET.Music
{
    public class AlbumsViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<AlbumModel> Items { get; private set; }
        public string AlbumUrl { get; private set; }
        public AlbumsViewModel()
        {
            this.Items = new ObservableCollection<AlbumModel>();
        }
        
        public bool IsDataLoaded { get; private set; }

        public void LoadData(string url)
        {
            //string url = "http://www.nhaccuatui.com/playlist/khong-loi-moi.html";
            AlbumUrl = url;

            this.Items.Add(new AlbumModel() { Avatar = "Assets/Icons/dvd-audio-extractor-300x300.png", Name = "Loading..." });
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            webRequest.BeginGetResponse(httpRequestCallback, webRequest);

            this.IsDataLoaded = true;
            
        }

        private void httpRequestCallback(IAsyncResult result)
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            try
            {
                WebResponse response = request.EndGetResponse(result);
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    string htmlCode = reader.ReadToEnd();
                    //Filter Data
                    //Regex regex = new Regex(@"href=.(?<url>http://www.woim.net/album/\d+/[a-z0-9-]+\.html).\stitle=.(?<title>([a-zA-Z0-9()-,!?&]|\.|\s)+).\starget=._blank.><img\ssrc=.http://data.woim.net/data.php\?src=(?<image>http://data.woim.net[a-zA-Z0-9-_/\.]+)&");
                    Regex titleurl = new Regex(@"<h3><a\shref=.(?<url>http://www.nhaccuatui.com/playlist/[a-zA-Z0-9-_\.]+html).\sclass=.name_song.\stitle=.(?<title>[^\""]+)");
                    MatchCollection titleMatchs = titleurl.Matches(htmlCode);
                    this.Items.Clear();
                    foreach (Match match in titleMatchs)
                    {
                        this.Items.Add(new AlbumModel(){Avatar = match.Groups["image"].ToString(), Name = match.Groups["title"].ToString(), Url = match.Groups["url"].ToString()});
                    }

                    Regex imageRegex = new Regex(@"\);""\ssrc=.(?<image>http://p.img.nct.nixcdn.com/playlist/[^""]+)");
                    MatchCollection imgMatchs = imageRegex.Matches(htmlCode);
                    int i = 0;
                    foreach (AlbumModel album in this.Items)
                    {
                        album.Avatar = imgMatchs[i++].Groups["image"].ToString();
                    }
                });
            }
            catch (WebException ex)
            {
                
            } 
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
